package org.scboy.rbac.service.imp;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.rbac.dao.RbacOrgRoleDao;
import org.scboy.rbac.dao.RbacUserRoleDao;
import org.scboy.rbac.service.UserRoleService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service("rbac_UserJobServiceImp")
public class UserRoleServiceImp implements UserRoleService {

	@Autowired
	EntityFactory factory;
	
	@Override
	public Page page(Model params) {
		RbacUserRoleDao dao=factory.getDao(RbacUserRoleDao.class);
		return dao.queryPage(params);
	}

	@Override
	public List<Model> list(Model params) {
		RbacUserRoleDao dao=factory.getDao(RbacUserRoleDao.class);
		return dao.queryList(params);
	}

	@Override
	public boolean add(String orId, String userId) {
		RbacUserRoleDao dao=factory.getDao(RbacUserRoleDao.class);
		RbacOrgRoleDao ordao=factory.getDao(RbacOrgRoleDao.class);
		long result=ordao.count(Model.create().add("orId", orId).add("userId", userId));
		if(result>0) {
			return false;
		}
		Model orgRole=ordao.get(Model.create().add("id", orId));
		if(orgRole==null)return false;
		Model userJob=Model.create();
		userJob.add("id", UUID.randomUUID().toString());
		userJob.add("orId", orId);
		userJob.add("code", orgRole.getString("code"));
		userJob.add("orgId", orgRole.getString("orgId"));
		userJob.add("userId", userId);
		userJob.add("addTime", new Date());
		long count=dao.insert(userJob);
		return count>0?true:false;
	}

	@Transactional
	@Override
	public boolean add(String orId, String[] userId) {
		RbacUserRoleDao dao=factory.getDao(RbacUserRoleDao.class);
		for (String uid : userId) {
			long count=dao.count(Model.create().add("orId", orId).add("userId", uid));
			if(count<=0) {
				add(orId, uid);
			}
		}
		return true;
	}

	@Override
	public boolean delete(String id) {
		RbacUserRoleDao dao=factory.getDao(RbacUserRoleDao.class);
		int result=dao.delete(Model.create().add("id", id));
		return result>0?true:false;
	}
}
